package sch.frog.behavioral.interpreter.calculator.expression.mid;

import sch.frog.behavioral.interpreter.calculator.expression.Expression;

public abstract class MidExpression implements Expression {

    protected abstract Expression getLeft();

    protected abstract Expression getRight();

    protected abstract void setLeft(Expression expression);

    protected abstract void setRight(Expression expression);

    @Override
    public boolean isLeaf(){
        return false;
    }

    @Override
    public Expression assembleTree(Expression expression) {
        Expression root;
        if(this.getPriority() == expression.getPriority()){
            // 如果两个表达式的优先级相等

            // 尝试将传入表达式作为根
            if(expression.createBranch(this)){
                root = expression;
            }else{
                // 尝试使用当前表达式作为根
                if(this.createBranch(expression)){
                    root = this;
                }else{
                    root = null;
                }
            }
        }else{
            Expression low;
            Expression high;
            if(this.getPriority() < expression.getPriority()){
                low = this;
                high = expression;
            }else{
                low = expression;
                high = this;
            }

            // 使用低优先级作为解析树的根
            root = low.createBranch(high) ? low : null;
        }

        return root;
    }

    public boolean createBranch(Expression expression){
        boolean hasRebuild = false;
        if(this.getRight() == null){    // 如果当前节点右侧已经有节点, 说明开始构造右子树, 这时, 不应再重新构造左子树
            Expression leftRoot = this.createLeftTree(expression);
            if(leftRoot != null){
                this.setLeft(leftRoot);
                hasRebuild = true;
            }
        }

        if(!hasRebuild) {    // 如果左子树重新构造失败, 说明左子树已完备, 开始构造右子树
            Expression rightRoot = this.createRightTree(expression);
            if(rightRoot != null){
                this.setRight(rightRoot);
                hasRebuild = true;
            }
        }

        return hasRebuild;
    }

    /**
     * 构造左子树
     * @param expression
     * @return
     */
    protected Expression createLeftTree(Expression expression){
        Expression root;
        Expression left = this.getLeft();
        if(left == null){
            root = expression;
        }else{
            root = left.assembleTree(expression);
        }
        return root;
    }

    /**
     * 构造右子树
     * @param expression
     * @return
     */
    protected Expression createRightTree(Expression expression){
        Expression root;
        Expression right = this.getRight();
        if(right == null){
            root = expression;
        }else{
            root = right.assembleTree(expression);
        }

        return root;
    }



}
